﻿using System;
using System.Globalization;

namespace FluentBinding.WinForms.Convertors
{
    public class DateTimeToString : ITypeConvertor<DateTime, string>
    {
        #region Fields

        private readonly string _format;
        private readonly IFormatProvider _formatProvider;

        #endregion

        #region Constructors

        public DateTimeToString()
        {
        }

        public DateTimeToString(IFormatProvider formatProvider)
            : this(null, formatProvider)
        {
        }

        public DateTimeToString(string format)
            : this(format, null)
        {
        }

        public DateTimeToString(string format, IFormatProvider formatProvider)
        {
            _format = format;
            _formatProvider = formatProvider;
        }

        #endregion

        #region ITypeConvertor<DateTime,string> Members

        public string Convert(DateTime value)
        {
            if (_format != null && _formatProvider != null)
                return value.ToString(_format, _formatProvider);

            if (_formatProvider != null)
                return value.ToString(_formatProvider);

            if (_format != null)
                return value.ToString(_format);

            return value.ToString();
        }

        public DateTime Convert(string value)
        {
            if (_format != null && _formatProvider != null)
                return DateTime.ParseExact(value, _format, _formatProvider);

            if (_formatProvider != null)
                return DateTime.Parse(value, _formatProvider);

            if (_format != null)
                return DateTime.ParseExact(value, _format, CultureInfo.CurrentCulture);

            return DateTime.Parse(value);
        }

        #endregion
    }
}